package com.cnxjs.shs4et.service.impl;

import com.cnxjs.shs4et.common.Result;
import com.cnxjs.shs4et.entity.Forum;
import com.cnxjs.shs4et.repository.ForumRepository;
import com.cnxjs.shs4et.service.ForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class ForumImpl implements ForumService {

    @Autowired
    private ForumRepository forumRepository;

    @Override
    public Result findAll(Pageable pageable) {
        return Result.success(forumRepository.findAll(pageable));
    }

    @Override
    public Result add(Forum forum) {
        Forum forumInDB = forumRepository.findByNameAndBlock(forum.getName(), forum.getBlock());
        if(forumInDB != null){
            return Result.error("论坛模块已存在");
        }
        else{
            forumRepository.save(forum);
        }
        return Result.success("创建成功");
    }

    @Override
    public Result update(Forum forum) {
        Forum forumInDB = forumRepository.findById(forum.getId());
        if (forumInDB != null) {
            forumInDB.setName(forum.getName());
            forumInDB.setBlock(forum.getBlock());
            forumRepository.save(forumInDB);
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @Override
    public Result delete(Integer id) {
        Forum forum =  forumRepository.findById(id);
        forum.setIsLocked(1);
        forumRepository.save(forum);
        return Result.success("删除成功");
    }
}
